package com.un.ebs.core.tenant;

import com.baomidou.mybatisplus.annotation.TableName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 检查所有实体类中哪些需要多租户处理，检查字段为 "tenantId"
 */
@Component
public class TenantTableIncludeReflectRunner implements ApplicationRunner{

    @Autowired
    private ApplicationContext applicationContext;

    @Order(1)
    @Override
    public void run(ApplicationArguments args) throws Exception {
        String[] beans = applicationContext.getBeanDefinitionNames();
        for (String bean : beans)
        {
            Class<?> cls = applicationContext.getBean(bean).getClass();
            TableName tableNameAnnotation = cls.getAnnotation(TableName.class);
            if(tableNameAnnotation!=null){
                for (Field field:cls.getDeclaredFields()) {
                    if (field.getName().equals("tenantId")) {
                        MybatisPlusConfig.includeTenantTable.add(tableNameAnnotation.value());
                    }
                }
            }
        }
        //System.out.println(MybatisPlusConfig.includeTenantTable);
    }

}
